package com.artezio.buyndrive.web;

import com.artezio.buyndrive.domain.Users;
import com.artezio.buyndrive.service.UserService;
import com.artezio.buyndrive.validator.UserValidator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import org.springframework.validation.Errors;

/**
 * User: spolyakov
 * Date: 07/18/12
 * Основной контроллер
 */

@Controller
public class MainController {

    @Autowired
    private UserService userService;
    
    @Autowired(required=true)
    private UserValidator userValidator;

    protected final Log logger = LogFactory.getLog(MainController.class);

    @RequestMapping("/")
    public ModelAndView begin(Model model) {
        model.addAttribute("user", new Users());
        return new ModelAndView("home");
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView login(@ModelAttribute("user") Users user,  BindingResult result, 
        Model model, HttpSession httpSession, Errors errors) {

        logger.info("Trying to login...");
        userValidator.validate(user, result);
        if(!result.hasErrors()){ 
            if (userService.login(user.getEmail(),
                user.getPassword()) == null) {
                errors.rejectValue("email", "email.error");
                return new ModelAndView("home");
            }else{
                httpSession.setAttribute("user", userService.get(user.getEmail()));
            }
            return new ModelAndView("redirect:/");
        }  
        return new ModelAndView("home");
    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public ModelAndView logout(HttpSession httpSession) {

        httpSession.invalidate();

        return new ModelAndView("redirect:/");
    }

    @RequestMapping("/personal")
    public ModelAndView personal(Map<String, Object> map, HttpServletRequest servletRequest) {

        logger.info("/personal");
        return new ModelAndView("personal");
    }
    
}